package com.twistinjava.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.twistinjava.exception.TwistinjavaException;

public class DBManager
{
	private static Log log = LogFactory.getLog(DBManager.class);

	/**
	 * Creates a new instance of DBManager
	 */
	private DBManager()
	{
	}

	/**
	 * Gets a connection to the database
	 * 
	 * @throws NamingException
	 * @throws SQLException
	 * @return
	 */
	public static Connection getConnection() throws TwistinjavaException
	{
		Connection conn = null;
		Context ctx = null;
		log.debug("Connecting to Database...");
		try
		{
			
			ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/twistinjava");

			if (ds != null)
			{
				log.debug("DataSource exist.");
				conn = ds.getConnection();
				if (conn != null)
					log.debug("Database connection successful.");
			} else
				log.error("DataSource \"java:comp/env/jdbc/twistinjava\" not found ");
		} catch (NamingException ne)
		{
			log.error(ne.getMessage());
			throw new TwistinjavaException(ne.getMessage(), ne);
		} catch (SQLException sqle)
		{
			log.error(sqle.getMessage());
			throw new TwistinjavaException(sqle.getMessage(), sqle);
		}
		return conn;
	}

}
